//
//  LoginViewController.m
//  ConfNav2.1
//
//  Created by Denis Parra on 1/12/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "NetUtil.h"

@implementation LoginViewController

@synthesize usernameField, passwordField;
@synthesize loginButton;
@synthesize loginMessage;
@synthesize managedObjectContext;
@synthesize contentID;


- (void)viewDidLoad {
    [super viewDidLoad];
	//NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	//NSString *userID = [prefs stringForKey:@"userid"];
	self.loginMessage.numberOfLines = 0;
	loginMessage.lineBreakMode = UILineBreakModeWordWrap;	
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    if ([prefs valueForKey:@"username"]!= nil ) {
        //NSLog(@"%@",[prefs valueForKey:@"username"]);
        usernameField.text = [prefs valueForKey:@"username"];
        if ([prefs valueForKey:@"password"]!=nil) {
            passwordField.text = [prefs valueForKey:@"password"];
        }
    }
}


// no need for portrait orientation

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */



- (IBAction) login: (id) sender
{
    
    
    //hide keyboard
    
	[passwordField resignFirstResponder];
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    
	
    
    //checkNetwork status;
    
    if ([NetUtil checkNetworkStatus:nil]== 0 ) {
        UIAlertView *alertfailure = [[UIAlertView alloc] initWithTitle:@"Error" message:@"No Network Connection! Please open your wifi or wwan connection"
                                                              delegate:self cancelButtonTitle:@"Return" otherButtonTitles:nil, nil];
        [alertfailure show];
        [alertfailure release];
        
        return;
        
    }
    
    
    if([usernameField.text isEqualToString:@""] || [passwordField.text isEqualToString:@""]){
        
        UIAlertView *alertfailure = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please input Username and Password"
                                                              delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alertfailure show];
        [alertfailure release];
        
        
    }else{
        NSString *postLogin =[NSString stringWithFormat:@"userEmail=%@&password=%@",usernameField.text, passwordField.text];
        NSString *hostStr = @"http://halley.exp.sis.pitt.edu/comet.dev/authentication/loginXML.jsp?";
        hostStr = [hostStr stringByAppendingString:postLogin];
        
        NSURL *url=[[NSURL alloc] initWithString:hostStr];
        
        NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
        [url release];
        
        [urlRequest setHTTPMethod:@"POST"];
        [urlRequest setHTTPBody:[postLogin dataUsingEncoding:NSASCIIStringEncoding]];
        [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        
        
        NSURLResponse *response;
        NSError *error;
        NSData *aData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
        
        
        NSString *serverOutput = [[NSString alloc] initWithData:aData encoding: NSASCIIStringEncoding];
        
        //NSString *statusText = nil, *nameText = nil, *userIDText = nil, *emailText = nil;
        
        NSString *statusText = nil, *userIDText = nil;
        //NSLog(@"Server Output: %@", serverOutput);
        
        TBXML * tbxml = [[TBXML alloc] initWithXMLString:serverOutput];
        
        TBXMLElement * root = tbxml.rootXMLElement;
        
        
        // if root element is valid
        if (root) {
            
            TBXMLElement * status = [TBXML childElementNamed:@"status" parentElement:root];
            if (status != nil) {
                
                // search for the status element within the root element's children
                statusText = [TBXML textForElement:status];
                if([statusText isEqualToString:@"OK"]){
                    // login success
                    
                    [prefs setObject:usernameField.text forKey:@"username"];
                    [prefs setObject:passwordField.text forKey:@"password"];
                    [prefs setObject:@"yes" forKey:@"authorized"];
                    
                    TBXMLElement *userID = [TBXML childElementNamed:@"userid" parentElement:root];
                    userIDText = [TBXML textForElement:userID];
                    [prefs setObject:userIDText forKey:@"userid"];
                                        
                    // show success
                    UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Congrats" message:@"You are authorized "
                                                                          delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                    
                    //NSLog(@"here");
                    [alertsuccess show];
                    [alertsuccess release];
                    NSMutableArray *controllers = [[self.navigationController.viewControllers mutableCopy] autorelease];
                    [controllers removeLastObject];
                    self.navigationController.viewControllers = controllers;
                    
                    //[self.navigationController popToRootViewControllerAnimated:YES];
                    
                }else{
                    //login failed
                    
                    UIAlertView *alertfailure = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Username or Password Incorrect"
                                                                          delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                    [alertfailure show];
                    [alertfailure release];
                }
                
                
                
            }
        }
        [serverOutput release];
        [tbxml release];
    }
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    //NSLog(@"Memory warning?");
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)dealloc {
    [contentID release];
    [usernameField release];
    [passwordField release];
    [loginButton release];
    [managedObjectContext release];
    //[loginIndicator release];
    [super dealloc];
}


@end
